package components {
import connection.Connectable;
import connection.SimpleConnectionPoint;

import flash.display.DisplayObject;
import flash.events.Event;
import flash.geom.Point;

import geditor.common.AbstractDrawComponent;
import geditor.common.AlignSource;
import geditor.common.DrawComponent;
import geditor.common.Selectable;

import mx.containers.Canvas;

public class BoxComponent extends AbstractDrawComponent implements DrawComponent, Selectable, Connectable, AlignSource {
    private var _display:Canvas = new Canvas();

    private var _center:SimplePoint = new SimplePoint();
    private var _width:Number = 100;
    private var _height:Number = 70;

    public function BoxComponent() {
        trace("BoxConnected");
        _connectionPoints = [new SimpleConnectionPoint(_center, this)];

        addEventListener("load", _load);
        addEventListener("select", _select);
        addEventListener("deselect", _deselect);

        _center.addEventListener("change", _refreshListener);
    }

    override public function refresh():void {
        if (_center.initialised) {
            _display.graphics.clear();

            _display.graphics.beginFill(0xCCCCCC);
            _display.graphics.lineStyle(1, 0x000000);

            _display.graphics.drawRect(_center.point.x - _width / 2, _center.point.y - _height / 2, _width, _height);
            _display.graphics.endFill();
        }
    }

    private function _deselect(evt:Event):void {
        tool.removeMovingPoint(_center);
    }

    private function _select(evt:Event):void {
        tool.addMovingPoint(_center);
    }

    private function _load(evt:Event):void {
        tool.startAlign(_center);
        var listener:Function = function(evt:Event):void {
            tool.removeEventListener("mouseDown", listener);
            tool.stopAlign();
            tool.finishCreating(true);
        };

        tool.addEventListener("mouseDown", listener);
    }

    public function get scalableDisplay():DisplayObject {
        return _display;
    }

    public function get notScalableDisplay():DisplayObject {
        return null;
    }

    public function get zIndex():int {
        return 10;
    }

    public function isComponent():Boolean {
        if (!_center.initialised) return false;
        var m:Point = new Point(_display.mouseX, _display.mouseY);
        return Math.abs(m.x - _center.point.x) < (_width / 2) && Math.abs(m.y - _center.point.y) < (_height / 2);
    }

    private var _connectionPoints:Array;

    public function get published():Array {
        return _connectionPoints;
    }
}
}